package project.service.impl;

import project.dao.BookDAO;
import project.dao.OrderDAO;
import project.dao.OrderItemDAO;
import project.dao.impl.BookDAOImpl;
import project.dao.impl.OrderDAOImpl;
import project.dao.impl.OrderItemDAOImpl;
import project.pojo.*;
import project.service.OrderService;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author d11yu
 */
public class OrderServiceImpl implements OrderService {
    private OrderDAO orderDAO = new OrderDAOImpl();
    private OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    private BookDAO bookDAO = new BookDAOImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) throws SQLException, NoSuchFieldException, IllegalAccessException {
        Order order = new Order(Order.generateOrderId(userId), new Date(), cart.getTotalPrice(), 0, userId);
        orderDAO.addOrder(order);

        List<OrderItem> orderItems = new ArrayList<>();
        List<Book> books = new ArrayList<>();
        for (CartItem cartItem : cart.getItems().values()) {
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), order.getId());
            orderItems.add(orderItem);
            // 更新数据库中的商品库存
            Book book = bookDAO.queryBookById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            books.add(book);
        }
        orderItemDAO.addOrderItems(orderItems);
        bookDAO.updateBooksSalesStockById(books);

        cart.clear();
        return order.getId();
    }
}
